//
//  PatronViewController.m
//  CS Inventory Manager
//
//  Created by Ian Smith on 2/10/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//

#import "PatronViewController.h"
#import "Patron.h"
#import "PatronDetailViewController.h"
#import "MDMultipleMasterDetailManager.h"
#import "EditPatronDetailViewController.h"
#import "AppDelegate.h"
#import "CheckoutRecordPatron.h"


@interface PatronViewController () {
    
    /* xml */
	NSURL* url;
	NSMutableData* requestData;
	NSMutableString* theData;
	NSXMLParser* fileParser;
	Patron *temp;
    CheckoutRecord *tempCheckout;
    CheckoutRecordPatron *tempPatron;
	BOOL noNetwork;
    
}
@end

@implementation PatronViewController

-(BOOL)refreshXML:(id)sender{
    
    self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Refreshing data..."];
    
    noNetwork = NO;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    // drop the patrons array (also drop it from AppDelegate)
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.patrons = nil;
    patrons = nil;
    //[self.tableView reloadData];
	patrons = [[NSMutableArray alloc] init];
    appDelegate.patrons = patrons;
    
    // get data from internet
    url = [[NSURL alloc] initWithString:@"http://www.cs.transy.edu/zoellers/inventory/listPatrons.php?secret=pass"];
	NSURLRequest *dataRequest = [NSURLRequest requestWithURL:url
												 cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
											 timeoutInterval:60];
	NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:dataRequest delegate:self];
	if (connection) {
		NSLog(@"refreshXML: Created connection request.");

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"MMM d, h:mm a"];
        NSString *lastUpdated = [NSString stringWithFormat:@"Last updated on %@",[formatter stringFromDate:[NSDate date]]];
        self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated];
        [self.refreshControl endRefreshing];
        
        return true;
	}
	else {
		NSLog(@"refreshXML: ERROR: Could not create connection request.");
		//Output no internet
        return false;
	}
	
}

- (void)awakeFromNib
{    

    self.clearsSelectionOnViewWillAppear = YES;
    self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
    
    [super awakeFromNib];
    [self refreshXML:nil];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    for (int x = 0; x < patrons.count; ++x) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.clearsSelectionOnViewWillAppear = NO;
    
    self.detailViewController = (PatronDetailViewController *)[[self.splitViewController.viewControllers objectAtIndex:1] topViewController];

    // allow pull down for refresh
    UIRefreshControl *refresh = [[UIRefreshControl alloc] init];
    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to Refresh"];
    [refresh addTarget:self action:@selector(refreshXML:) forControlEvents:UIControlEventValueChanged];
    self.refreshControl = refresh;
    
}

-(void)viewDidAppear:(BOOL)animated
{
    // probably not the final code..
    self.detailViewController = (PatronDetailViewController *)[[self.splitViewController.viewControllers objectAtIndex:1] topViewController];
    
    // make PatronViewController the delegate for PatronDetailViewController
    [self.detailViewController setDelegate:self];
    
}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    if (editing) {
        //Do stuff going into the editing view
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addItem:)];
    }
    else {
        self.navigationItem.leftBarButtonItem = nil;
    }
}

//Function that responds to a tap on the "Add" button while in editing view
-(void)addItem:sender {
    Patron *newPatron = [[Patron alloc] init];
    [newPatron setActive:YES];
    [newPatron setPatronType:@"Student"];
    
    [self performSegueWithIdentifier:@"AddPatron" sender:newPatron];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    EditPatronDetailViewController *nextController = segue.destinationViewController;
    nextController.thePatron = sender;
    [nextController setDelegate:self];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return patrons.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    Patron *patron = patrons[indexPath.row];
    NSLog(@"checking string %@",patron.lastName);
    NSMutableString *name = [[NSMutableString alloc] initWithString:patron.lastName];
    [name appendString:@", "];
    [name appendString:patron.firstName];
    cell.textLabel.text = name;
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // make the web call to delete
        // set all params for URL
        NSString *uid = [NSString stringWithFormat:@"%d", [[patrons objectAtIndex:indexPath.row] patronId]];
        
        // generate the URL and use %20 encoding
        NSString *urlStr = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/patron.php?secret=pass&id=%@",uid];
        NSString *final = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSLog(@"The url is: >>>>>%@<<<<<", final);
        
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:final]];
        
        // make web request and catch error
        NSError * e;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
        
        // log the value returned from the web server
        NSString *value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"return from web: %@", value);
        
        // delete locally too
        [patrons removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Patron *object = patrons[indexPath.row];
    self.detailViewController.detailItem = object;
}

/********************************************************************
                  for xml parsing
 ********************************************************************/

//connection finished loading it's data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	// DEBUGGING: NSLog(@"GRABBED DATA%@", requestData);
    if (requestData) {
        NSLog(@"connectionDidFinishLoading: Retrieved XML data. Beginning XML parsing process.");
    } else {
        NSLog(@"connectionDidFinishLoading: ERROR: No XML data retrieved.");
    }
	//allocate file parser
	fileParser = [[NSXMLParser alloc] initWithData:requestData];
	
	//set current object as delegate
	[fileParser setDelegate:self];
	//start parsing
	[fileParser parse];
	 NSLog(@"connectionDidFinishLoading: Ending XML parsing process");
    fileParser = nil;
	
	
}


//Connection failed
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	 NSLog(@"\t\tconnection DidFailWithError: ERROR: Connection failed, trigger notification.");
	//Connection failed, tell the user
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Unable to connect." message:@"Your device is unable to connect to the network. Please check your network connection and try again." delegate:self cancelButtonTitle:@"Dismiss"  otherButtonTitles:nil, nil];
	[alert show];
	alert = nil;
	noNetwork = YES;
	[self.tableView reloadData];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	
}
//Connection Started
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	//allocate a place to store the data until it is whole
	requestData = [[NSMutableData alloc] init];
	[requestData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	//Append data
	[requestData appendData:data];
}
//Found start tag
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
	if ([elementName isEqual:@"xml"]) {
		//Allocate a string that will hold the data
		theData = [[NSMutableString alloc] init];
	}
	else if ([elementName isEqual:@"patron"]) {
		//allocate a temporary variable to hold the data until it is ready to be stored in the array
		temp = [[Patron alloc] init];
	} else if ([elementName isEqual:@"checkout"]) {
        if (![temp checkoutsActive]) {
            // alloc the array for the first checkout
            [temp setCheckoutsActive:[[NSMutableArray alloc] init]];
        }
        
        tempCheckout = [[CheckoutRecord alloc] init];
        tempCheckout.patrons = [[NSMutableArray alloc] init];
        
    } else if ([elementName isEqual:@"copatron"]) {
        // allocate a new checkout patron
        tempPatron = [[CheckoutRecordPatron alloc] init];
    }
    
	if (![elementName isEqual:@"xml"]) {
		//black the string
		[theData setString:@""];
	}
}
//Found end tag while parsing
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	//Check the end element name and store it in theData to the appropriate variable
	if ([elementName isEqual:@"xml"]) {
        
	}
	else if ([elementName isEqual:@"lastName"]) {
		[temp setLastName:[[NSString alloc] initWithString:theData]];
	}
    else if ([elementName isEqual:@"firstName"]) {
		[temp setFirstName:[[NSString alloc] initWithString:theData]];
	}
	else if ([elementName isEqual:@"email"]) {
		[temp setEmail:[[NSString alloc] initWithString:theData]];
	}
	else if ([elementName isEqual:@"phone"]) {
		[temp setTelephone:[[NSString alloc] initWithString:theData]];
	}
	else if ([elementName isEqual:@"id"]) {
		[temp setPatronId:[theData intValue]];
	}
    else if ([elementName isEqual:@"type"]) {
		[temp setPatronType:[[NSString alloc] initWithString:theData]];
	}
    else if ([elementName isEqual:@"active"]) {
        if ([theData isEqual:@"Y"]) {
            // active
            [temp setActive:YES];
        } else {
            // not active
            [temp setActive:NO];
        }
    } else if ([elementName isEqual:@"checkoutID"]) {
        [tempCheckout setCheckoutID:[theData intValue]];
    } else if ([elementName isEqual:@"itemType"]) {
		[tempCheckout setItemType:[[NSString alloc] initWithString:theData]];
	} else if ([elementName isEqual:@"itemModel"]) {
		[tempCheckout setItemModel:[[NSString alloc] initWithString:theData]];
	} else if ([elementName isEqual:@"itemAssetID"]) {
        [tempCheckout setAssetNo:[[NSString alloc] initWithString:theData]];
    } else if ([elementName isEqual:@"patronName"]) {
        [tempPatron setName:[[NSString alloc] initWithString:theData]];
    } else if ([elementName isEqual:@"patronEmail"]) {
        [tempPatron setEmail:[[NSString alloc] initWithString:theData]];
    } else if ([elementName isEqual:@"patronId"]) {
        [tempPatron setId:[theData intValue]];
	} else if ([elementName isEqual:@"outDate"]) {
        NSString *dateString = [[NSString alloc] initWithString:theData];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        // this is imporant - we set our input date format to match our input string
        // if format doesn't match you'll get nil from your string, so be careful
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        // voila!
		[tempCheckout setOutDate:[dateFormatter dateFromString:dateString]];
    } else if ([elementName isEqual:@"dueDate"]) {
        NSString *dateString = [[NSString alloc] initWithString:theData];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        // this is imporant - we set our input date format to match our input string
        // if format doesn't match you'll get nil from your string, so be careful
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        // voila!
		[tempCheckout setDueDate:[dateFormatter dateFromString:dateString]];
    } else if ([elementName isEqual:@"returnDate"]) {
		NSString *dateString = [[NSString alloc] initWithString:theData];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        // this is imporant - we set our input date format to match our input string
        // if format doesn't match you'll get nil from your string, so be careful
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        // voila!
		[tempCheckout setInDate:[dateFormatter dateFromString:dateString]];
    } else if ([elementName isEqual:@"outNotes"]) {
		[tempCheckout setOutNotes:[[NSString alloc] initWithString:theData]];
    } else if ([elementName isEqual:@"inNotes"]) {
        [tempCheckout setInNotes:[[NSString alloc] initWithString:theData]];
    } else if ([elementName isEqual:@"profName"]) {
        [tempCheckout setProfName:[[NSString alloc] initWithString:theData]];
    } else if ([elementName isEqual:@"copatron"]) {
        // add the temp patron to the array of patrons
        [[tempCheckout patrons] addObject:tempPatron];
        tempPatron = nil;
    } else if ([elementName isEqual:@"checkout"]) {
        // add the temp checkout to the array
        [[temp checkoutsActive] addObject:tempCheckout];
        tempCheckout = nil;
    } else if ([elementName isEqual:@"patron"]) {
        NSLog(@"\t\tparser didEndElement: Retrieved Patron with last name %@",[temp lastName]);
		[patrons addObject:temp];
		temp = nil;
	}
	
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
	[theData appendString:string];
}

- (void)parserDidEndDocument:(NSXMLParser *)parse
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	 NSLog(@"\t\tparserDidEndDocument: Data retrieved, reloading table.");
	[self.tableView reloadData];
}

@end
